const express = require('express');
const router = express.Router()
const app = express();
const port = 3000;
const bodyParser = require('body-parser');
const request = require('request');


app.use(bodyParser.urlencoded({
	extend: false
}));
app.use(bodyParser.json());
app.use(router);
app.all("*",function(req,res,next){
	//设置允许跨域的域名，*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", "*");
	// res.header("Access-Control-Allow-Headers", "X-Requested-With");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    next();
})

app.get('/api/createQRCode', async (req, res) => {
	let params = {
		"access_token": req.query.access_token,
		"appname": req.query.appname,
		"path": req.query.path,
		"icon": req.query.icon
	}
	let result = await requestPost(params,"https://developer.toutiao.com/api/apps/qrcode");
	res.send({
		'data': 1000,
		"message": '已生成',
		"result": result,
	})
})

function requestPost(requestData, url){
	return new Promise((resolve, reject) => {
		var options = {
			url: url,
			method: 'POST',
			json: true,
			timeout: 3000,
			headers: {
				'Content-Type': 'application/json;charset=utf-8'
			},
			encoding: "base64",
			body: requestData
		}
		request(options, function(error, response, body){
			if(!error && response.statusCode == 200){
				resolve('data:image/png;base64,'+body)
			}else{
				reject(error)
			}
		})
	})
}
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
